package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author HLF
 * @version V1.0
 * @package utils
 * @date 2021/10/29 8:33
 * 获取数据库连接的工具类，使用德鲁伊数据库连接池
 */
public class JDBCUtils {


    //1.Druid数据库连接池获取连接
    private static DataSource source1;
    static{
        try {
            Properties pros = new Properties();

            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");

            pros.load(is);

            source1 = DruidDataSourceFactory.createDataSource(pros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getDruidConnection() throws SQLException {

        Connection conn = source1.getConnection();;
        return conn;
    }

    //2.关闭连接和Statement的操作
    public static void closeResource(Connection conn, Statement ps){
        try {
            if(ps != null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
